package net.flydy.ywxcx.wxcloudrun.common;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.PhoneUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;


/**
 * @author flydy
 */
public class Utils {
    public static String uuid() {
        return UUID.randomUUID().toString(true);
    }

    public static boolean isMobile(String str) {
        return PhoneUtil.isMobile(str);
    }

    public static String formatMobile(String str) {
        str = StringUtils.removeStart(str, "+86");
        str = StringUtils.removeStart(str, "86");
        return str;
    }

    public static String getIp(HttpServletRequest httpReq) {
        return httpReq.getRemoteAddr();
    }

    public static byte[] longToByteArray(long l) {
        byte[] b = new byte[8];
        b[7] = (byte) (l);
        l >>>= 8;
        b[6] = (byte) (l);
        l >>>= 8;
        b[5] = (byte) (l);
        l >>>= 8;
        b[4] = (byte) (l);
        l >>>= 8;
        b[3] = (byte) (l);
        l >>>= 8;
        b[2] = (byte) (l);
        l >>>= 8;
        b[1] = (byte) (l);
        l >>>= 8;
        b[0] = (byte) (l);
        return b;
    }

    public static long byteArrayToLong(byte[] b){
        return ( ( (long) b[7]) & 0xFF) +
                ( ( ( (long) b[6]) & 0xFF) << 8) +
                ( ( ( (long) b[5]) & 0xFF) << 16) +
                ( ( ( (long) b[4]) & 0xFF) << 24) +
                ( ( ( (long) b[3]) & 0xFF) << 32) +
                ( ( ( (long) b[2]) & 0xFF) << 40) +
                ( ( ( (long) b[1]) & 0xFF) << 48) +
                ( ( ( (long) b[0]) & 0xFF) << 56);
    }

    public static void sleepThenRun(long st, Runnable runnable) {
        try {
            Thread.sleep(st);
        } catch (Exception e) {
        }
        runnable.run();
    }

    public static String getP2PSessionId(long uid1, long uid2) {
        if (uid1 >= uid2) {
            return uid1 + "_" + uid2;
        } else {
            return uid2 + "_" + uid1;
        }
    }
}
